<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<meta charset="utf-8">
	<link href="../../../Scripts/easyUI15/themes/default/easyui.css" rel="stylesheet" type="text/css" />
	<link href="../../../Scripts/easyUI15/themes/icon.css" rel="stylesheet" type="text/css" />
	<!--<link href="/WF/Comm/JS/EasyUI/themes/default/layout.css" rel="stylesheet" type="text/css" />-->
	<style>
		html, body
		{
			margin: 0px;
			padding: 0px;
		}
		div.top
		{
			width: 100%;
			height: 25px;
			/*background-color: #ffeeee;*/
		}
		div.left
		{
			width: 350px;
			/*background-color: #eeffee;*/
		}
		div.center
		{
			width: calc(100% - 200px);
			background-color: #eeeeff;
		}
	</style>
	<script src="../../WF/Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
	<script src="../../WF/Scripts/easyUI15/jquery.easyui.min.js" type="text/javascript"></script>
	<script src="../../WF/Scripts/EasyUIUtility.js" type="text/javascript"></script>
	<script type="text/javascript" src="../../WF/Scripts/QueryString.js"></script>
	<script type="text/javascript" src="../../WF/Scripts/config.js"></script>
	<script type="text/javascript" src="./Excel.js"></script>
	<script type="text/javascript">
		var Events = {
			//选中区域: ["SheetSelectionChange"],
			输入_Enter: ["a34", "SheetChange", "SheetSelectionChange"],
			输入_Tab: ["a34", "SheetChange", "SheetSelectionChange"],

			Delete: ["SheetChange", "a34"],
			DeleteRow: ["SheetChange", "a34"],
			DeleteColumn: ["SheetChange", "a34"],

			RightClick_删除: ["SheetBeforeRightClick", /*出现右键菜单，点击删除*/"SheetChange", "a34"],
			RightClickOnRowHead_删除: ["SheetSelectionChange", "SheetBeforeRightClick", /*出现右键菜单，点击删除*/"SheetChange", "a34"],
			RightClickOnColumnHead_删除: ["SheetSelectionChange", "SheetBeforeRightClick", /*出现右键菜单，点击删除*/"SheetChange", "a34"],

			Name_删除 :[/*公式-命名管理器-选中-删除-关闭*/ "UnkonwID:0x00000a34"]
		};
	</script>
	<script language="javascript" for="WebOffice1" event="NotifyCtrlReady">
		WebOffice1_NotifyCtrlReady();
		///初始化excel
		function WebOffice1_NotifyCtrlReady() {
			console.group("WebOffice1_NotifyCtrlReady");
			woObj = document.getElementById("WebOffice1");
			//var url = "../../../../../DataUser/FrmOfficeTemplate/" + _FormNo + ".xlsx";
			var url;
			$.ajax({
				async: false,
				url: Handler + "?DoType=GetFileUrl&FK_MapData=" + _FormNo + "&m=" + Math.random(),
				dataType: 'html',
				success: function(data) {
					url = data;
				}
			});
			console.log("WebOffice1_NotifyCtrlReady | url: " + url);
			if (url.indexOf("err@") > -1) {
				alert(url);
				woObj.LoadOriginalFile("", "xlsx");
			}else{
				var ext = url.substr(url.lastIndexOf(".") + 1, url.length - url.lastIndexOf(".") + 1);
				console.log("WebOffice1_NotifyCtrlReady | ext: " + ext);
				woObj.LoadOriginalFile(url, ext); //参数 ext 必需！
			}
			woObj.HideMenuItem(
				0x01		//新建
				//+ 0x02		//打开
				+ 0x04		//保存
				+ 0x10		//打印
				+ 0x20		//打印预览
				+ 0x1000	//全屏
				//+ 0x4000	//显示/隐藏菜单
				+ 0x2000	//返回
			);
			excel = new Excel(woObj);
			ConsoleLogOnSelect();
			console.groupEnd();
		}
	</script>
	<script language="javascript" for="WebOffice1" event="NotifyWordEvent(eventname)">
		WebOffice1_NotifyWordEvent(eventname);
		//WebOffice事件监听
		function WebOffice1_NotifyWordEvent(eventname) {
			switch (eventname) {
				case "DocumentBeforeSave":
					if (vNoSave) {
						woObj.lContinue = 0;
						alert("此文档已经禁止保存");
					} else {
						woObj.lContinue = 1;
					}
					break;
				case "DocumentBeforePrint":
					if (vNoPrint) {
						woObj.lContinue = 0;
						alert("此文档已经禁止打印");
					} else {
						woObj.lContinue = 1;
					}
					break;
				case "WindowSelectionChange":
					if (vNoCopy) {
						woObj.lContinue = 0;
						//alert("此文档已经禁止复制");
					} else {
						woObj.lContinue = 1;
					}
					break;
				case "DocumentBeforeClose":
					if (vClose == 0) {
						woObj.lContinue = 0;
					} else {
						//alert("word");
						woObj.lContinue = 1;
					}
					break;
				case "SheetSelectionChange": //变更选中区域//使用代码执行操作时也会触发/Q如何排除？
					ConsoleLogOnSelect();
					if (excel.IsSingle()) {
						//选中accordion
						var tableId = excel.GetCellInName();
						if(tableId == null){
							tableId = "main";
							$("#aa").accordion("select", "表单字段");
						}
						else{
							$("#aa").accordion("select", "子表：" + tableId);
						}
						//选中行
						var columnName = excel.GetName();
						if (columnName != null) {
							$("#" + tableId).datagrid("selectRecord", columnName);
						}
					} else {
					}
					break;
				case "WorkbookNewSheet": //新建sheet页（UnknownID:0x0000061a/UnknownID:0x00000619：切换sheet页）
					break;
				default:
					// console.log("WebOffice1_NotifyWordEvent | case default | eventname: " + eventname);
					break;
			}
			console.log("WebOffice1_NotifyWordEvent | eventname: " + eventname);
		}
	</script>
	<script type="text/javascript">

		function ConsoleLogOnSelect() {
			console.group("function ConsoleLogOnSelect");
			console.log("excel.GetSheet():" + excel.GetSheet());
			console.group("ActiveCell");
			console.log("excel.GetCell_$():" + excel.GetCell_$());
			console.log("excel.GetCell():" + excel.GetCell());
			console.log("excel.GetCellS():" + excel.GetCellS());
			//console.log("excel.GetCellR1C1S():" + excel.GetCellR1C1S());
			console.log("excel.GetValue():" + excel.GetValue());
			console.log("excel.GetName():" + excel.GetName());
			//console.log("excel.GetCellInName():" + excel.GetCellInName());
			console.groupEnd();
			console.group("Selection");
			console.log("excel.GetRange():" + excel.GetRange());
			console.log("excel.GetRangeName():" + excel.GetRangeName());
			console.groupEnd();
			console.groupEnd();
		}

		var _FormNo;
		var woObj, excel;
		// var form, tableMain;
		$(document).ready(function () {
			_FormNo = GetQueryString("FK_MapData");
			//布局
			$("body").layout();
			//主表字段
			InitTable("main", _FormNo);
			//子表
			InitSub();
		});

		//初始化子表
		function InitSub() {
			$.ajax({
				//async: false,
				url: Handler + "?DoType=GetSubTables&FK_MapData=" + _FormNo + "&m=" + Math.random(),
				dataType: 'json',
				success: function (data) { //[{id:},{}]
					console.log(typeof (data)); //object
					for (var i in data) {
						CreateSubDom(data[i].No, null, false);
					}
				}
			});
		}

		//创建子表dom
		function CreateSubDom(tableId, range, isSelect) { //TODO: 将range信息保存到数据库
			var btnRefresh = document.createElement("button");
			btnRefresh.innerText = "刷新";
			btnRefresh.onclick = function () {
				RefreshGrid(tableId);
			};

			var btnShowRange = document.createElement("button");
			btnShowRange.innerText = "显示子表区域";
			btnShowRange.onclick = function () {
				ShowSubRange(tableId);
			};
			var table = document.createElement("table");
			table.id = tableId;
			table.style = "overflow: auto; padding: 0;";
			var div = document.createElement("div");
			div.appendChild(btnRefresh);
			div.appendChild(btnShowRange);
			div.appendChild(table);
			$("#aa").accordion("add", {
				title: "子表：" + tableId,
				content: div,
				selected: isSelect
			});
			InitTable(table.id, tableId);
		}

		function RefreshGrid(id){
			$("#" + id).datagrid("reload");
		}

		//在excel中显示子表的区域
		function ShowSubRange(tableId) {
			console.log("ShowSubRange | 显示子表区域：" + tableId);
			var range = excel.GetRangeByName(tableId);
			if(range != null){
				excel.SetSelection(range.split("!")[0].replace("=",""), range.split("!")[1]);
			}
		}

		//初始化grid
		function InitTable(tableId, id) {
			$("#" + tableId).datagrid({
				url: "../handler.ashx?DoType=FiledsList_Init&FK_MapData=" + id + "&m=" + Math.random(), //TODO: 改成专用的？
				idField: 'KeyOfEn',
				striped: true,
				showFooter: false,
				singleSelect: true,
				columns: [[
						{ field: 'KeyOfEn', title: '字段名', width: 50, align: 'left' },
						{ field: 'Name', title: '中文名', width: 85, align: 'left' },
						// { field: 'LGTypeText', title: '类型', width: 50, align: 'left' },
						{ field: 'AtPara', title: '单元格', width: 70, align: 'left',
							formatter: function(value,row,index){
								return GetAtPara(value, "BindCell");
							}
						},
						{ field: '操作', title: '操作', width: 57, align: 'left',
							formatter: function(value,row,index){
								// if (row.user){
								// 	return row.user.name;
								// } else {
								// 	return value;
								// }
								var bindCell = GetAtPara(row.AtPara, "BindCell");
								if(bindCell == null || bindCell == "") {
									return "<button onclick=\"Insert('" + tableId + "','" + index + "','" + row.KeyOfEn + "')\" title='插入到当前单元格'>插入</button>";

								}else{
									// var btn = document.createElement("button");
									// btn.innerText = "解绑";
									// btn.title = "解除单元格绑定";
									// btn.onclick = function(){
									// 	Unbind(tableId,row);
									// };
									// return btn; //前端会显示“[object HTMLButtonElement]”
									return "<button onclick=\"Unbind('" + tableId + "','" + row.MyPK + "','" + row.KeyOfEn + "')\" title='解除单元格绑定'>解绑</button>";
								}
							}
						}
				]],
				onSelect: function (index, row) {
					//if (row.Sheet && row.Cell) {
					//	//选中sheet/单元格
					//	excel.SetSelection(row.Sheet, row.Cell);
					//}
					var bindCell = GetAtPara(row.AtPara, "BindCell");
					if(bindCell != null && bindCell != ""){
						var arrayAddress = bindCell.split("!");
						var sheet = arrayAddress[0].replace("=", "");
						var cell = arrayAddress[1];
						excel.SetSelection(sheet, cell);
					}
				}
			});
		}

		function GetAtPara(atPara,name){
			if(atPara){
				// return atPara;//for test
				var aryAtPara = atPara.split("@");
				for(var i = 1; i < aryAtPara.length; i++){
					if(aryAtPara[i].split("=")[0] == name){
						return aryAtPara[i].substr(aryAtPara[i].indexOf("=") + 1);
					}
				}
			}
			// return null;
		}

		//打开【字段列表】页面
		function OpenFieldsList() {
		    var url = "../../FoolFormDesigner/BatchEdit.htm?FK_MapData=" + _FormNo;
			var w = window.showModalDialog(url, 'ass', 'dialogHeight: 500px; dialogWidth: 700px;center: yes; help: no');
			alert("重新加载【字段列表】");
		}
	</script>
	<!--__________________________________________________________________________________________Methods-->
	<script type="text/javascript">
		//选中字段
		function SetColumnSelection(id) {
			//TODO: 会触发 datagrid.onSelect 导致循环执行
			$('#main').datagrid("selectRecord", id);
		}

		//解除字段与单元格的绑定
		function Unbind(tableId,pk,name){
			//更改数据库数据
			if(confirm("确定要解除单元格绑定吗？")){
				var result = false;
				$.ajax({
				    async: false,
				    dataType: 'html',
					url: Handler + "?DoType=RemoveBindCell&MyPK=" + pk + "&m=" + Math.random(),
					// dataType: 'json',
					success: function (data) {
						if (data.indexOf("err@") > -1) {
							alert(data);
							result = false;
						} else {
							//删除命名
							result = excel.DelName(name);
						}
					}
				});
				if(result){
					RefreshGrid(tableId);
				}

				//TODO: 枚举/外键 删除“数据有效性”
			}
		}


		//grid行的“插入”方法//表id(主子)/
		function Insert(tableId,rowIndex,columnName){
			var row = $("#"+tableId).datagrid("getData").rows[rowIndex];
			//TODO: 判断row本身是否存在绑定单元格信息，->信息是否有效？
			var bindCell = GetAtPara(row.AtPara, "BindCell");
			if(bindCell != null){
				var actualBindCell = excel.GetRangeByName(columnName);
				if(actualBindCell == null){ //没有该字段对应的命名 -> 继续执行

				}else {
					if("=" + bindCell == actualBindCell){ //绑定单元格信息有效 -> 

					}else{ 
					/*/绑定单元格信息无效（row的绑定信息与实际不符）-> 
						1.清除绑定信息|清除实际命名|绑定当前单元格
						2.清除绑定信息|使用实际命名
						3.使用绑定信息|清除实际命名|重新绑定
					*/

					}
				}
			}

			//判断是否选中单个单元格
			if (excel.IsSingle() != true) {
				alert("请选中『单个单元格』创建字段！");
				return false;
			}
			//单元格是否已绑定字段
			var cellName = excel.GetName();
			if (cellName != null) { //已绑定字段
				alert("该单元格已存在关联字段，不能重复创建字段！");
				return false;
			}
			//判断单元格是否位于某子表区域内
			var cellInTable = excel.GetCellInName();
			if (cellInTable === null) {
				cellInTable = "main";
			}
			if(tableId != cellInTable){
				if(tableId == "main")
					alert("当前单元格位于子表'"+cellInTable+"'区域内，不能将主字段'"+columnName+"'插入该单元格！");
				else
					alert("当前单元格不在子表'"+tableId+"'区域内，不能将字段'"+columnName+"'插入该单元格！");
				return false;
			}
			var insertExcelResult = false;
			switch (row.LGType) {
				case 0: //普通
					insertExcelResult = InsertNormal(tableId,row);
					break;
				case 1: //枚举
					insertExcelResult = InsertEnum(tableId,row);
					break;
				case 2: //外键
					insertExcelResult = InsertFkey(tableId,row);
					break;
				default:
					break;
			}
			if(insertExcelResult){
				SetBindCell(row.MyPK);
			}
			RefreshGrid(tableId);
		}

		//在当前单元格插入普通字段//tableId(gridId)/columnName:(object)字段
		function InsertNormal(tableId,column){
			if(typeof(column)=="object" && column.KeyOfEn!=null) {
				//单元格命名
				excel.SetName(column.KeyOfEn);
				if(tableId != "main"){ //为子表时
					excel.SetValue(column.Name); //子表表头
				}
				return true;
			}else{
				console.error("InsertNormal | 字段信息错误！");
				alert("字段信息错误！");
				return false;
			}
		}

		//在当前单元格插入枚举字段 //TODO: 处理enumKey=column.KeyOfEn的情况
		function InsertEnum(tableId,column){
			//1.设置枚举/外键区域
			//1.1.建立枚举/外键sheet页
			excel.AddSheet("MetaData");
			excel.HideSheet("MetaData");
			//1.2.获取枚举值列表
			// var enumKey = "EnumName" + Math.round(Math.random() * 10000);
			// var enumList = GetEnumList(enumKey);
			var enumKey = column.UIBindKey;
			var enumList = GetEnumList(enumKey);
			//1.3.枚举区域赋值
			//TODO: 先判断EnumKey是否已存在
			var c1 = 1;
			//while (excel.GetValue("MetaData", excel.ConvertInt2Letter(c1) + 1) != null) { //改为根据命名判断
			while (excel.GetCellInName("MetaData", "$" + excel.ConvertInt2Letter(c1) + "$1") != null) {
				c1 += 1;
			}
			var cL = excel.ConvertInt2Letter(c1);
			for (var i in enumList) {
				excel.SetValue(enumList[i].Lab, "MetaData", cL + (parseInt(i) + 1));
			}
			//1.4.枚举区域命名
			excel.SetRangeName(enumKey,
				"MetaData",
				"$" + cL + "$1:$" + cL + "$" + enumList.length
			//"$" + cL + ":$" + cL //不可设置整列！作为数据有效性使用时，可以填入序列以外的值（应不允许）！
			);

			//2.字段
			if(tableId == "main"){
				//2.1.字段(单元格)本身的命名
				excel.SetName(column.KeyOfEn);
				//2.2.字段(单元格)本身的数据有效性
				excel.SetValidation(enumKey);
			}else{
				//2.0.子表标题
				excel.SetValue(column.Name);
				//2.1.字段(单元格)本身的命名
				excel.SetName(column.KeyOfEn);
				//2.2.子表字段(单元格)的数据有效性
				var tableRange = excel.GetRangeByName(tableId); //e.g. =Sheet1!$B$3:$E$5 => [=Sheet1!,B,3:,E,5]
				var add = excel.GetCell(); //e.g. $C$2
				var aryAdd = add.split("$");
				var range = "$" + aryAdd[1] + "$" + (parseInt(aryAdd[2]) + 1) + ":$" + aryAdd[1] + "$" + tableRange.split("$")[4];
				excel.SetValidation(enumKey,
					tableRange.split("!")[0].replace("=",""),
					range);
			}
			return true;
		}

		//在当前单元格插入外键字段
		function InsertFkey(tableId,column){
			//1.设置外键区域
			//1.1.建立外键sheet页
			excel.AddSheet("MetaData");
			excel.HideSheet("MetaData");
			//1.2.获取外键值列表
			var fKey = column.UIBindKey;
			var fList = GetFkeyList(column.MyPK, fKey);
			//1.3.外键区域赋值
			//TODO: 先判断Fkey是否已存在
			var c1 = 1;
			//while (excel.GetValue("MetaData", excel.ConvertInt2Letter(c1) + 1) != null) { //改为根据命名判断
			while (excel.GetCellInName("MetaData", "$" + excel.ConvertInt2Letter(c1) + "$1") != null) {
				c1 += 1;
			}
			var cL = excel.ConvertInt2Letter(c1);
			for (var i in fList) {
				// excel.SetValue(fList[i][column.UIRefKeyText], "MetaData", cL + (parseInt(i) + 1)); //TODO: 因数据库（MS SQL）中保存的UIRefKeyText为『NAME』,无法正常取值，故暂时写死为『Name』:
				excel.SetValue(fList[i]["Name"], "MetaData", cL + (parseInt(i) + 1)); //TODO: 其他数据库的大小写情况？
			}
			//1.4.外键区域命名
			excel.SetRangeName(fKey,
				"MetaData",
				"$" + cL + "$1:$" + cL + "$" + fList.length
			//"$" + cL + ":$" + cL //不可设置整列！作为数据有效性使用时，可以填入序列以外的值（应不允许）！
			);

			//2.字段
			if(tableId == "main"){
				//2.1.字段(单元格)本身的命名
				excel.SetName(column.KeyOfEn);
				//2.2.字段(单元格)本身的数据有效性
				excel.SetValidation(fKey);
			}else{
				//2.0.子表标题
				excel.SetValue(column.Name);
				//2.1.字段(单元格)本身的命名
				excel.SetName(column.KeyOfEn);
				//2.2.子表字段(单元格)的数据有效性
				var tableRange = excel.GetRangeByName(tableId); //e.g. =Sheet1!$B$3:$E$5 => [=Sheet1!,B,3:,E,5]
				var add = excel.GetCell(); //e.g. $C$2
				var aryAdd = add.split("$");
				var range = "$" + aryAdd[1] + "$" + (parseInt(aryAdd[2]) + 1) + ":$" + aryAdd[1] + "$" + tableRange.split("$")[4];
				excel.SetValidation(fKey,
					tableRange.split("!")[0].replace("=",""),
					range);
			}
			return true;
		}

		//保存关联单元格信息到数据库
		function SetBindCell(pk){
			var result = false;
			$.ajax({
				async: false,
				url: Handler + "?DoType=SetBindCell&MyPK=" + pk + "&Cell=" + escape(excel.GetCellS()) + "&m=" + Math.random(),
				dataType: 'json',
				success: function (data) {
					if (data.indexOf("err@") > -1) {
						alert(data);
						result = false;
					} else {
						result = true;
					}
				}
			});
			return result;
		}

		//新增字段//表(主/子)
		function NewColumn(table) {
			console.log("NewColumn | 在此表中新建字段：" + table);

			//TODO: 需要注意：字段“英文名”不能和单元格地址类似，例如 ZD1

			var FK_MapData = table == "main" ? _FormNo : table;
			var url = "../FieldTypeList.htm?FK_MapData=" + FK_MapData;

			//打开新建子表页面
			// var newcolumn = showModalDialog(url);
			// return newcolumn;
			// // //error: easyui的方法会产生图层错误
			// // OpenEasyUiDialog(url, 'eudlgframe', '新建字段', 760, 470, 'icon-edit', true, function () {
			// // 	var innerWin = document.getElementById('eudlgframe').contentWindow;
			// // 	//$('#' + txtId).val(innerWin.getReturnText());
			// // 	//$('#' + hiddenId).val(innerWin.getReturnValue());
			// // });
			//for test:
			// return {"MyPK":"CSExcelBDDtl6_RDT","FK_MapData":table=="main"?_FormNo:table,"KeyOfEn":"ceshi_normal","Name":"测试普通字段","DefVal":"","UIContralType":0,"MyDataType":7,"LGType":0,"LGTypeText":"普通","UIWidth":100,"UIHeight":23,"MinLen":0,"MaxLen":300,"UIBindKey":"","UIRefKey":"无","UIRefKeyText":"","UIVisible":"0","UIIsEnable":"0","UIIsLine":"0","UIIsInput":"0","IsSigan":0,"X":5,"Y":5,"GUID":"","Tag":"1","EditType":1,"ColSpan":1,"GroupID":2091,"Idx":999,"AtPara":""};
			// return {"MyPK":"CSExcelBDDtl6_RDT","FK_MapData":table=="main"?_FormNo:table,"KeyOfEn":"ceshi_enum","Name":"测试枚举字段（费用类型）","DefVal":"","UIContralType":0,"MyDataType":7,"LGType":1,"LGTypeText":"枚举","UIWidth":100,"UIHeight":23,"MinLen":0,"MaxLen":300,"UIBindKey":"FYLX","UIRefKey":"无","UIRefKeyText":"","UIVisible":"0","UIIsEnable":"0","UIIsLine":"0","UIIsInput":"0","IsSigan":0,"X":5,"Y":5,"GUID":"","Tag":"1","EditType":1,"ColSpan":1,"GroupID":2091,"Idx":999,"AtPara":""};
			//BP.Port.Emps
			return {"MyPK":"CSExcelBDDtl6_RDT","FK_MapData":table=="main"?_FormNo:table,"KeyOfEn":"ceshi_enum","Name":"测试枚举字段（费用类型）","DefVal":"","UIContralType":0,"MyDataType":7,"LGType":2,"LGTypeText":"外键","UIWidth":100,"UIHeight":23,"MinLen":0,"MaxLen":300,"UIBindKey":"BP.Port.Emps","UIRefKey":"无","UIRefKeyText":"","UIVisible":"0","UIIsEnable":"0","UIIsLine":"0","UIIsInput":"0","IsSigan":0,"X":5,"Y":5,"GUID":"","Tag":"1","EditType":1,"ColSpan":1,"GroupID":2091,"Idx":999,"AtPara":""};
		}

		//新建子表并返回子表id
		function NewSub() {
			var subId = prompt("请输入子表ID，要求值唯一。", _FormNo + "Dtl1");
			if (subId == null) {
				return false;
			} else if (subId == "") {
				alert('子表ID不能为空，请重新输入！');
				//NewSub(); //因需要返回值，故不可再次调用自身
				return false;
			}

			//请求服务器创建子表
			$.ajax({
				async: false,
				url: Handler + "?DoType=NewSub&FK_MapData=" + _FormNo + "&SubId=" + subId + "&m=" + Math.random(),
				dataType: 'html',
				success: function (data) {
					if (data.indexOf("err@") > -1) {
						alert(data);
						//NewSub(); //因需要返回值，故不可再次调用自身
						return false;
					} else {
						subId = data;
					}
				}
			});
			return subId;
		}

		//获取枚举列表
		function GetEnumList(enumkey) {
			// return [{Lab:"abc"}, {Lab:"def"}, {Lab:"xyz"}]; //for test
			var enumlist;
			$.ajax({
				async: false,
				url: Handler + "?DoType=GetEnumList&EnumKey=" + enumkey + "&m=" + Math.random(),
				dataType: 'json',
				success: function (data) {
					if (data.indexOf("err@") > -1) {
						alert(data);
						return false;
					} else {
						enumlist = data;
					}
				}
			});
			return enumlist;
		}

		//获取外键列表
		function GetFkeyList(pk,Fkey){
			var fkeyList;
			$.ajax({
				async: false,
				url: Handler + "?DoType=GetFkeyList&FK_MapData=" + _FormNo + "&MyPK=" + pk + "&Fkey=" + Fkey + "&m=" + Math.random(),
				dataType: 'json',
				success: function (data) {

				    fkeyList = data;

//					if (data.indexOf("err@") > -1) {
//						alert(data);
//						return false;
//					} else {
//						fkeyList = data;
//					}
				}
			});
			return fkeyList;
		}

		//// 根据前缀与字段名，返回他的区域对象，如果没有就返回空.//CopyFrom:D:\ccflow\CCFlow\WF\CCForm\FrmExcel.aspx
		function getRangeName(sName, sCcflowPrefix, aCurrSheets) {
			/// <summary>获取指定字段所标识的单元格区域名称对象</summary>
			/// <param name="sName" type="String">字段名称</param>
			/// <param name="sCcflowPrefix" type="String">ccflow的名称标识字符串</param>
			/// <param name="aCurrSheets" type="Array">要检索的sheet集合</param>
			var nms, //当前工作簿的命名区域集合.
				na,
				na_len;
			for (var s = 0; s < aCurrSheets.length; s++) {
				nms = aCurrSheets[s].Names;
				na = aCurrSheets[s].Name + '!' + sCcflowPrefix + sName;
				na_len = na.length;

				for (var i = 1; i <= nms.Count; i++) {
					if (aCurrSheets[s].Names(i).Name == na ||
					(aCurrSheets[s].Names(i).Name.length > na_len &&
						aCurrSheets[s].Names(i).Name.substr(0, na_len) == na &&
						aCurrSheets[s].Names(i).Name.substr(na_len).split('_').length < 3)) {    //此处过滤掉有相同前缀的属性
						return aCurrSheets[s].Names(i);
					}
				}
			}
			return null;
		}

		//保存文件到服务器
		function SaveFile() {
			// 初始化Http引擎
			document.all.WebOffice1.HttpInit();
			// 添加相应的Post元素 
			//document.all.WebOffice1.HttpAddPostString("DoType", "SaveFile"); //会使用HttpRequest.Form方式传递，而handler的通用『属性.』无法正常读取
			//document.all.WebOffice1.HttpAddPostString("FK_MapData", _FormNo);
			// 添加上传文件
			document.all.WebOffice1.HttpAddPostCurrFile("File ", "");
			// 提交上传文件
			var url = location.href.substr(0, location.href.lastIndexOf("/") + 1) + Handler + "?DoType=SaveFile&FK_MapData=" + _FormNo + "&m=" + Math.random();
			var returnValue = document.all.WebOffice1.HttpPost(url);
			if (returnValue == "true") {
				alert("保存成功！");
			} else {
				alert("保存失败！" + returnValue);
			}
		}

	</script>
	<!--__________________________________________________________________________________________Events-->
	<script type="text/javascript">
		//保存按钮事件
		function onclick_btnSave() {
			SaveFile();
		}

		//新建字段
		function onclick_btnNewColumn() {
			//判断是否选中单个单元格
			if (excel.IsSingle() != true) {
				alert("请选中『单个单元格』创建字段！");
				return false;
			}
			//单元格是否已绑定字段
			var cellName = excel.GetName();
			if (cellName != null) { //已绑定字段
				alert("该单元格已存在关联字段，不能重复创建字段！");
				return false;
			}
			//根据当前单元格判断是否为子表
			var cellInTable = excel.GetCellInName();
			// console.log("onclick_btnNewColumn | in name: " + name);
			if (cellInTable === null) {
				cellInTable = "main";
			}
			//创建并获取字段
			var newcolumn = NewColumn(cellInTable);
			if(newcolumn){
				var insertExcelResult = false;
				switch (newcolumn.LGType) {
					case 0: //普通
						insertExcelResult = InsertNormal(cellInTable,newcolumn);
						break;
					case 1: //枚举
						insertExcelResult = InsertEnum(cellInTable,newcolumn);
						break;
					case 2: //外键
						insertExcelResult = InsertFkey(cellInTable,newcolumn);
						break;
					default:
						break;
				}
				if(insertExcelResult == true){
					//保存关联信息 //TODO: 如果新建字段页面改进了（执行了此操作），则此处不用再处理一边
					SetBindCell(newcolumn.MyPK);
				}
				//切换手风琴
				var accPart = cellInTable == "main" ? "主表字段" : "子表：" + cellInTable;
				$("#aa").accordion("select",accPart);

				//刷新Gird并选中行
				$("#" + cellInTable).datagrid("reload");
				$("#" + cellInTable).datagrid("selectRecord",newcolumn.KeyOfEn);
			}
		}

		//新建枚举/外键字段//for test
		function onclick_btnNewColumnEnum() {
			console.group("onclick_btnNewColumnEnum");

			//1.设置枚举/外键区域
			//1.1.建立枚举/外键sheet页
			excel.AddSheet("MetaData");
			excel.HideSheet("MetaData");
			//1.2.获取枚举值列表
			var enumkey = "EnumName" + Math.round(Math.random() * 10000); //EnumKey
			var enumList = GetEnumList(enumkey);
			//1.3.枚举区域赋值
			//TODO: 先判断EnumKey是否已存在
			var c1 = 1;
			//while (excel.GetValue("MetaData", excel.ConvertInt2Letter(c1) + 1) != null) { //改为根据命名判断
			while (excel.GetCellInName("MetaData", "$" + excel.ConvertInt2Letter(c1) + "$1") != null) {
				c1 += 1;
			}
			var cL = excel.ConvertInt2Letter(c1);
			for (var i in enumList) {
				excel.SetValue(enumList[i].Lab, "MetaData", cL + (parseInt(i) + 1));
			}
			//1.4.枚举区域命名
			excel.SetRangeName(enumkey,
				"MetaData",
				"$" + cL + "$1:$" + cL + "$" + enumList.length
			//"$" + cL + ":$" + cL //不可设置整列！作为数据有效性使用时，可以填入序列以外的值（应不允许）！
			);

			//2.字段
			//2.1.字段(单元格)本身的命名
			excel.SetName("ColumnNameOf" + enumkey);
			//2.2.字段(单元格)本身的数据有效性
			excel.SetValidation(enumkey);

			console.groupEnd();
		}

		//新建子表
		function onclick_btnNewSub() {
			//判断是否选中单个单元格
			if (excel.IsSingle() == true) {
				alert("无法在『单个单元格』中创建子表，请选中一个区域！");
				return false;
			}
			//判断是否已有命名
			var rangeName = excel.GetRangeName(); //TODO: 是否遍历所有选中单元格，不允许同一个单元格在两个子表中？
			if (rangeName != null) {
				alert("该区域已存在关联子表，不能重复创建！");
				return false;
			}
			//创建子表
			var newTableId = NewSub();
			if (newTableId != false) { //Q: 直接使用“if(newTableId)”且“newTableId=false”时为什么会继续执行？
				//命名
				excel.SetRangeName(newTableId);
				CreateSubDom(newTableId);
			}
		}

		//关闭/刷新页面前询问
		window.onbeforeunload = function () {
			if (confirm("是否需要保存？")) {
				//保存文档
				SaveFile();
				//关闭文档
				woObj.CloseDoc(0);
			} else {
				if (confirm("关闭本页面将丢失所有更改，确定关闭？")) {
					//关闭文档
					woObj.CloseDoc(0);
				}
				else {
					return "请选择“留在本页”！"; //ie //xTODO: other browser?x暂时只支持IE
				}
			}
		}
	</script>
</head>
<body>
	<div data-options="region:'north'" class="top">
		<button onclick="onclick_btnSave();">
			保存</button>
		<button onclick="JavaScript:alert('预览功能尚在开发中！');">
			预览（开发中）</button>
		<button onclick="JavaScript:alert('复制功能尚在开发中！');">
			复制（开发中）</button>
		<button onclick="onclick_btnNewColumn();">
			新建字段</button>
		<button onclick="onclick_btnNewColumnEnum();">
			新建枚举/外键字段（测试用）</button>
		<button onclick="onclick_btnNewSub();">
			新建明细表</button>
	</div>
	<div data-options="region:'west'" class="left">
		<div id="aa" class="easyui-accordion" style="width: 100%; height: 100%;">
			<div title="表单字段" style="overflow: auto; padding: 0;">
				<button onclick="RefreshGrid('main');">
					刷新</button>
				<button onclick="OpenFieldsList();">
					维护明细(测试用)</button>
				<table id="main" border="0" cellpadding="0" cellspacing="0">
				</table>
			</div>
		</div>
	</div>
	<div data-options="region:'center'" class="center">
		<object id="WebOffice1" height="99%" width='100%' classid='clsid:E77E049B-23FC-4DB8-B756-60529A35FAD5'
			codebase='/WF/Activex/WebOffice.cab#V7.0.1.0'>
			<param name='_ExtentX' value='6350'>
			<param name='_ExtentY' value='6350'>
		</object>
	</div>
</body>
</html>
